import { defineComponent, ref, reactive, onMounted } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import {
  ElCard,
  ElRow,
  ElCol,
  ElLink,
  ElForm,
  ElFormItem,
  ElInput,
  ElSwitch,
  ElDatePicker,
  ElSelect,
  ElOption,
  ElIcon,
  ElButton,
  ElMessage,
  ElDropdown,
  ElDropdownMenu,
  ElDropdownItem
} from 'element-plus'
import { Plus, WarningFilled, ArrowDown } from '@element-plus/icons-vue'
import { handleTrim } from '~/utils/util'
import { uniqWith } from 'lodash'

import type { FormInstance, UploadUserFile } from 'element-plus'
import type { FormValuesType } from './typings'
import type {
  equipmentBrandEnum,
  equipmentModelEnum
  // powerFacilitiesEnum
} from '~/store/monitor/typings'
import AliIcon from '~/components/AliIocn'
import SaasTitle from '~/components/SaasTitle'
import styles from './index.module.scss'
import useVuexGetters from '~/hooks/useVuexGetters'
import BaseUpload from '~/components/ProForm/BaseUpload'
import MapView from '../components/map'
// 连接参数设置
import ConnectSet from './connectSet'
// 工作参数设置
import WorkSet from './workSet'
// 回路参数设置
import LoopSet from './loopSet'
// 警报参数设置
import AlarmSet from './alarmSet'
// 事件参数设置
import EventSet from './eventSet'
// 其它参数设置
import OtherSet from './otherSet'
//  配电设施选择
import DistrabutionList from './distrabutionList'

export default defineComponent(function Demo() {
  const store = useStore()
  const router = useRouter()
  const ruleFormRef = ref<FormInstance>()
  const form = reactive<FormValuesType>({
    categoryId: '1451114885786066946', //  暂时只有回路监控箱，所以先写死了id
    useStatus: 1
  })
  const state = reactive<any>({
    ConnectSetVisible: false,
    WorkSetVisible: false,
    LoopSetVisible: false,
    AlarmSetVisible: false,
    EventSetVisible: false,
    OtherSetVisible: false,
    DistrabutionVisible: false,
    connectParam: null,
    workParam: null,
    loopParam: null,
    eventParam: null,
    alarmParam: null,
    otherParam: null,
    IssueCommandList: [],
    QueryCommandList: []
  })
  const fileList = ref<UploadUserFile[]>([])
  const equipmentState = useVuexGetters('equipment', [
    'equipmentBrandOpt',
    'equipmentModelOpt',
    'powerFacilitiesOpt'
  ])
  const policeState = useVuexGetters('police', ['workAreaOpt'])
  const marker = reactive({
    lng: '',
    lat: ''
  })
  const userState = useVuexGetters('user', ['userAddressInfo'])

  onMounted(() => {
    //  设备品牌
    store.dispatch('equipment/GetTenantBrandList')
    //  配电设施
    store.dispatch('equipment/SelectBoxListByName')
    //  所属工区
    store.dispatch('police/SelectAreaNameBoxList')

    const { type, id } = router.currentRoute.value.query
    if (type === 'edit') {
      infoAjax(id)
      paramsInfoAjax(id)
      getIssueCommand(id)
      getQueryCommand(id)
    }
  })
  //  详情数据
  const infoAjax = async (id: any) => {
    const { code, data } = await store.dispatch('equipment/DeviceView', { id })
    if (code === 200) {
      form.name = data.name
      form.code = data.code
      form.useStatus = data.useStatus
      form.deliverDate = data.deliverDate
      form.brandId = data.brandId
      form.brandName = data.brandName
      form.modelId = data.modelId
      form.modelName = data.modelName
      form.distributionId = data.distributionId
      form.distributionName = data.distributionName

      form.areaId = data.areaId
      form.areaName = data.areaName
      form.address = data.address
      form.lon = data.lon
      form.lat = data.lat
      marker.lng = data.lon
      marker.lat = data.lat

      form.power = data.power
      form.memo = data.memo

      form.runStatus = data.runStatus
      if (data.imageUrl) {
        form.imageUrl = data.imageUrl
        fileList.value = data.imageUrl.split(',')
      }
    }
  }
  //  附图
  const handleUploadSuccess = (file: Record<string, any>) => {
    const link = file?.data?.link
    if (link) {
      fileList.value?.push(link)
    }
  }
  const handleRemoveUploadFile = (file: Record<string, any>) => {
    const link = file?.url
    if (link) {
      fileList.value = fileList.value?.filter((item) => item !== link)
    }
  }
  //  设备品牌选择
  const brandChange = (value: any) => {
    form.modelId = ''
    equipmentState.equipmentBrandOpt.value.forEach(
      (item: { name: string | undefined; id: any }) => {
        if (item.id === value) {
          form.brandName = item.name
          //  设备型号
          store.dispatch('equipment/GetTenantModelList', { deviceBrandId: item.id })
        }
      }
    )
  }
  //  设备型号选择
  const modelChange = (value: any) => {
    equipmentState.equipmentModelOpt.value.forEach(
      (item: { name: string | undefined; id: any }) => {
        if (item.id === value) {
          form.modelName = item.name
        }
      }
    )
  }
  //  配电设施选择
  const distrabutionChange = (item: any) => {
    form.distributionId = item.id
    form.distributionName = item.name
    form.areaId = item.workAreaId
    form.areaName = item.workAreaName
    form.address = item.address
    form.lon = item.lon
    form.lat = item.lat
    marker.lng = item.lon
    marker.lat = item.lat
  }
  const onDistrabution = () => {
    state.DistrabutionVisible = !state.DistrabutionVisible
  }
  //  所属工区选择
  const areaChange = (value: string) => {
    policeState.workAreaOpt.value.forEach((item: any) => {
      if (item.id === value) {
        form.areaName = item.name
      }
    })
  }
  //  返回
  const goBack = () => {
    fileList.value = []
    ruleFormRef.value?.resetFields()
    router.go(-1)
  }
  //  保存
  const submit = () => {
    if (!ruleFormRef.value) return
    ruleFormRef.value.validate(async (valid) => {
      if (valid) {
        const { id, type } = router.currentRoute.value.query
        if (fileList.value.length > 0) {
          form.imageUrl = fileList.value.join(',')
        }
        if (!form.lon && !form.lat && !form.address) {
          ElMessage({
            message: '经纬度、地址不能为空',
            type: 'success'
          })
          return
        }
        const parmas = JSON.parse(JSON.stringify(form))
        let url = ''
        if (type === 'add') {
          url = 'equipment/DeviceAdd'
        } else {
          url = 'equipment/DeviceUpdate'
        }
        const { code } = await store.dispatch(url, { ...parmas, id })
        if (code === 200) {
          ElMessage({
            message: '操作成功',
            type: 'success'
          })
          router.go(-1)
        }
      } else {
        return false
      }
    })
  }

  //  参数设置
  const handleParamsSet = (value: string) => {
    state[value] = !state[value]

    const { id } = router.currentRoute.value.query
    paramsInfoAjax(id)
  }
  //  参数详情数据
  const paramsInfoAjax = async (id: any) => {
    try {
      const { data } = await store.dispatch('equipment/ViewByDeviceIdGet', { id })
      //  连接参数
      state.connectParam = JSON.parse(data.connectParam)
      //  工作参数
      state.workParam = JSON.parse(data.workParam)
      //  回路参数
      state.loopParam = JSON.parse(data.loopParam)
      //  事件参数
      state.eventParam = JSON.parse(data.eventParam)
      //  警报参数
      state.alarmParam = JSON.parse(data.alarmParam)
      //  其它参数
      state.otherParam = JSON.parse(data.otherParam)
      // console.log(state.otherParam);
    } catch (error) {}
  }
  //  查询监控箱下发指令
  const getIssueCommand = async (id: any) => {
    try {
      const { data } = await store.dispatch('equipment/GetIssueCommandGet', { id })
      state.IssueCommandList = data
    } catch (error) {}
  }
  //  查询监控箱查询指令
  const getQueryCommand = async (id: any) => {
    try {
      const { data } = await store.dispatch('equipment/GetQueryCommandGet', { id })
      state.QueryCommandList = data
    } catch (error) {}
  }
  //  下拉操作/查询操作
  const handleIssue = async (item: any) => {
    try {
      const { id } = router.currentRoute.value.query
      const params = {
        commandId: item.commandId,
        deviceId: id
      }
      await store.dispatch('runmap/ExcuteCommandParamPost', params)
    } catch (error) {}
  }

  const selectAddressRef = ref()
  const selectAddressOptionsRef = ref()
  const selectAddressSearchRef = ref<string>()
  const mapViewRef = ref()
  // 地址选择下拉框输入停止后回调
  const handleFilterAddressSearch = (value: string) => {
    selectAddressSearchRef.value = handleTrim(value)
    handleSearchAddressSelectList()
  }
  // 点击地图左上角查询按钮的时候回调 | 在
  const handleSearchAddressSelectList = (e?: Event) => {
    if (e) e.stopPropagation()
    const placeSearch = new mapViewRef.value.aMapRef.PlaceSearch({
      city: userState.userAddressInfo.value.city,
      citylimit: false
    }) // 构造地点查询类
    placeSearch.search(
      selectAddressSearchRef.value,
      (status: string, result: Record<string, any>) => {
        selectAddressOptionsRef.value =
          status === 'complete' && result.info === 'OK'
            ? uniqWith(
                result.poiList.pois,
                (item: { name: string }, nextItem: { name: string }) => item.name === nextItem.name
              )
            : []
      }
    )
  }
  // 切换地址选择回调
  const handleChangeAddressSelect = (value: string) => {
    const str = `${value[0]},${value[1]}`
    form.lon = value[0]
    form.lat = value[1]
    // // 再去匹配对应的值并获取对应的设施地址
    form.address = selectAddressOptionsRef.value?.find(
      (item: any) => `${item?.location?.lng},${item?.location?.lat}` === str
    )?.address
    // // 更新地图标记点位置
    marker.lng = form.lon
    marker.lat = form.lat
    const timer = setTimeout(() => {
      mapViewRef.value.setMarkersByPropsMarkers()
      clearTimeout(timer)
    }, 0)
  }
  //  设置经纬度
  const onLnglatSet = (row: any) => {
    form.lon = row.lng
    form.lat = row.lat
    //  逆解析地址
    const geocoder = new mapViewRef.value.aMapRef.Geocoder({
      city: '全国',
      radius: 1000,
      extensions: 'all'
    })
    geocoder.getAddress(row, (status: string, result: any) => {
      if (status === 'complete' && result.info === 'OK') {
        if (result && result.regeocode) {
          form.address = result.regeocode.formattedAddress
        }
      }
    })
  }

  return () => {
    const { type } = router.currentRoute.value.query
    return (
      <ElCard>
        <ElRow gutter={50} style="margin-bottom: 30px;">
          <ElCol span={8}>
            <SaasTitle type="primary">
              <ElLink underline={false} class={styles['edit-title']}>
                基本信息
              </ElLink>
            </SaasTitle>
          </ElCol>
          <ElCol span={16}>
            <SaasTitle type="primary">
              <ElLink underline={false} class={styles['edit-title']}>
                地图
              </ElLink>
            </SaasTitle>
          </ElCol>
        </ElRow>

        <ElRow gutter={50} class={styles['form-con']}>
          <ElCol span={8}>
            <ElForm ref={ruleFormRef} model={form} label-width="120px">
              <ElRow>
                <ElCol span={24}>
                  <ElFormItem
                    label="设备名称"
                    prop="name"
                    rules={[
                      { required: true, message: '请输入设备名称', trigger: 'blur' },
                      { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
                    ]}
                  >
                    <ElInput v-model={form.name} placeholder="请输入设备名称" clearable></ElInput>
                  </ElFormItem>
                </ElCol>
                <ElCol span={24}>
                  <ElFormItem
                    label="设备编号"
                    prop="code"
                    rules={[
                      { required: true, message: '请输入设备编号', trigger: 'blur' },
                      { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
                    ]}
                  >
                    <ElInput
                      v-model={form.code}
                      placeholder="请输入设备编号"
                      clearable
                      disabled={form.runStatus === 1 || form.runStatus === 2}
                    ></ElInput>
                  </ElFormItem>
                </ElCol>
                <ElCol span={24}>
                  <ElFormItem
                    label="投运状态"
                    prop="useStatus"
                    rules={[{ required: true, message: '请选择投运状态', trigger: 'blur' }]}
                  >
                    <ElSwitch v-model={form.useStatus} active-value={1} inactive-value={0} />
                  </ElFormItem>
                </ElCol>
                <ElCol span={24}>
                  <ElFormItem label="投运日期">
                    <ElDatePicker
                      v-model={form.deliverDate}
                      type="date"
                      disabled={form.useStatus === 0}
                      placeholder="请输入投运日期"
                    />
                  </ElFormItem>
                </ElCol>
                <ElCol span={24}>
                  <ElFormItem
                    label="设备品牌"
                    prop="brandId"
                    rules={[{ required: true, message: '请选择设备品牌', trigger: 'change' }]}
                  >
                    <ElSelect
                      v-model={form.brandId}
                      clearable
                      onChange={brandChange}
                      placeholder="请选择设备品牌"
                    >
                      {equipmentState.equipmentBrandOpt?.value?.map((item: equipmentBrandEnum) => (
                        <ElOption key={item?.id} label={item?.name} value={item?.id} />
                      ))}
                    </ElSelect>
                  </ElFormItem>
                </ElCol>
                <ElCol span={24}>
                  <ElFormItem
                    label="设备型号"
                    prop="modelId"
                    rules={[{ required: true, message: '请选择设备型号', trigger: 'change' }]}
                  >
                    <ElSelect
                      v-model={form.modelId}
                      clearable
                      onChange={modelChange}
                      placeholder="请选择设备型号"
                    >
                      {form.brandId &&
                        equipmentState.equipmentModelOpt?.value?.map((item: equipmentModelEnum) => (
                          <ElOption key={item?.id} label={item?.name} value={item?.id} />
                        ))}
                    </ElSelect>
                  </ElFormItem>
                </ElCol>
                <ElCol span={24}>
                  <ElFormItem
                    label="配电设施"
                    prop="distributionName"
                    rules={[{ required: true, message: '请选择配电设施', trigger: 'blur' }]}
                  >
                    {/* <ElSelect
                      v-model={form.distrabutionId}
                      filterable
                      clearable
                      onChange={distrabutionChange}
                      placeholder="请选择配电设施"
                      style="width: 75%;"
                    >
                      {equipmentState.powerFacilitiesOpt?.value?.map(
                        (item: powerFacilitiesEnum) => (
                          <ElOption key={item?.id} label={item?.name} value={item?.id} />
                        )
                      )}
                    </ElSelect> */}
                    <ElInput
                      v-model={form.distributionName}
                      placeholder="请输入配电设施"
                      clearable
                      style="width: 75%;"
                    ></ElInput>
                    &nbsp;&nbsp;
                    <ElButton type="primary" onClick={onDistrabution}>
                      <ElIcon>
                        <Plus />
                      </ElIcon>
                    </ElButton>
                  </ElFormItem>
                </ElCol>
                <ElCol span={24}>
                  <ElFormItem label="所属区域">
                    {/* <ElInput v-model={form.areaName} disabled></ElInput> */}
                    <ElSelect
                      v-model={form.areaId}
                      clearable
                      placeholder="请选择所属区域"
                      onChange={areaChange}
                      filterable
                    >
                      {policeState.workAreaOpt?.value?.map((item: any) => (
                        <ElOption key={item?.id} label={item?.name} value={item?.id} />
                      ))}
                    </ElSelect>
                  </ElFormItem>
                </ElCol>
                <ElCol span={24}>
                  <ElFormItem label="理论负荷">
                    <ElInput
                      v-model={form.power}
                      placeholder="请输入理论负荷"
                      clearable
                      {...{ maxlength: 6 }}
                      onInput={(value) => {
                        form.power = value.replace(/[^\d]/g, '')
                      }}
                      style="width: 90%;"
                    ></ElInput>{' '}
                    &nbsp;&nbsp;W
                  </ElFormItem>
                </ElCol>
                <ElCol span={24}>
                  <ElFormItem label="备注">
                    <ElInput
                      v-model={form.memo}
                      placeholder="请输入备注"
                      show-word-limit
                      {...{ maxlength: 200 }}
                      type="textarea"
                    />
                  </ElFormItem>
                </ElCol>
                <ElFormItem label="图片">
                  <BaseUpload
                    listType="picture-card"
                    accept=".jpg, .png"
                    limit={12}
                    fileList={fileList.value?.map?.((item) => ({
                      name: '图片',
                      url: item,
                      response: {
                        data: {
                          link: item
                        }
                      }
                    }))}
                    onSuccess={handleUploadSuccess}
                    onRemove={handleRemoveUploadFile}
                    v-slots={{
                      tip: () => (
                        <section>
                          <ElLink type="info" underline={false} icon={<WarningFilled />}>
                            支持最多上传12张图片
                          </ElLink>
                        </section>
                      )
                    }}
                  >
                    <ElIcon>
                      <Plus />
                    </ElIcon>
                    点击上传
                  </BaseUpload>
                </ElFormItem>
              </ElRow>
            </ElForm>
          </ElCol>
          <ElCol span={16} class={styles['map-location']}>
            <MapView
              style="height: 500px; margin-bottom: 30px;"
              ref={mapViewRef}
              marker={marker}
              id="equipmentMap"
              onLnglatSet={onLnglatSet}
            />
            <ElFormItem class={styles['map-location-select-address']}>
              <ElSelect
                v-model={selectAddressRef.value}
                filterable
                suffixIcon={<AliIcon type="icon-sousuo" />}
                remote
                defaultFirstOption
                clearable
                placeholder="请输入地址"
                remoteMethod={handleFilterAddressSearch}
                onChange={handleChangeAddressSelect}
              >
                {selectAddressOptionsRef.value?.map((item: any) => (
                  <ElOption
                    class={styles['map-location-option-address']}
                    key={item?.id}
                    label={item?.name}
                    value={[item?.location?.lng, item?.location?.lat]}
                  >
                    <ElLink underline={false} type="info">
                      <AliIcon type="icon-ditudingwei" />
                    </ElLink>
                    <section class="option-text">
                      <b>{item?.name}</b>
                      <p>{item?.address}</p>
                    </section>
                  </ElOption>
                ))}
              </ElSelect>
            </ElFormItem>
            <ElRow gutter={50}>
              <ElCol span={12}>
                <ElFormItem required label="设备经度">
                  <ElInput v-model={form.lon} disabled></ElInput>
                </ElFormItem>
              </ElCol>
              <ElCol span={12}>
                <ElFormItem required label="设备纬度">
                  <ElInput v-model={form.lat} disabled></ElInput>
                </ElFormItem>
              </ElCol>
            </ElRow>
            <ElRow>
              <ElCol span={24}>
                <ElFormItem required label="设备地址">
                  <ElInput v-model={form.address} disabled></ElInput>
                </ElFormItem>
              </ElCol>
            </ElRow>
          </ElCol>
        </ElRow>

        {type === 'edit' && (
          <ElRow gutter={50} style="margin-bottom: 30px;">
            <ElCol span={24}>
              <SaasTitle type="primary">
                <ElLink underline={false} class={styles['edit-title']}>
                  参数设置
                </ElLink>
              </SaasTitle>
            </ElCol>
            <ElCol span={24} style="margin: 20px 0;">
              <ElButton
                type="primary"
                size="default"
                onClick={() => handleParamsSet('ConnectSetVisible')}
              >
                连接参数设置
              </ElButton>
              <ElButton
                type="primary"
                size="default"
                onClick={() => handleParamsSet('WorkSetVisible')}
              >
                工作参数设置
              </ElButton>
              <ElButton
                type="primary"
                size="default"
                onClick={() => handleParamsSet('LoopSetVisible')}
              >
                回路参数设置
              </ElButton>
              <ElButton
                type="primary"
                size="default"
                onClick={() => handleParamsSet('AlarmSetVisible')}
              >
                警报参数设置
              </ElButton>
              <ElButton
                type="primary"
                size="default"
                onClick={() => handleParamsSet('EventSetVisible')}
              >
                事件参数设置
              </ElButton>
              <ElButton
                type="primary"
                size="default"
                onClick={() => handleParamsSet('OtherSetVisible')}
              >
                其它参数设置
              </ElButton>
            </ElCol>
            <ElCol span={24}>
              <SaasTitle type="primary">
                <ElLink underline={false} class={styles['edit-title']}>
                  设备操作
                </ElLink>
              </SaasTitle>
            </ElCol>
            <ElCol span={24} style="margin: 20px 0;">
              <ElDropdown
                v-slots={{
                  dropdown: () => (
                    <ElDropdownMenu>
                      {state.IssueCommandList.map((item: any) => (
                        <ElDropdownItem onClick={() => handleIssue(item)}>
                          {item.commandName}
                        </ElDropdownItem>
                      ))}
                    </ElDropdownMenu>
                  )
                }}
              >
                <ElButton type="primary" size="default">
                  下发操作{' '}
                  <ElIcon class="el-icon--right">
                    <ArrowDown />
                  </ElIcon>
                </ElButton>
              </ElDropdown>
              &nbsp;&nbsp;&nbsp;
              <ElDropdown
                v-slots={{
                  dropdown: () => (
                    <ElDropdownMenu>
                      {state.QueryCommandList.map((item: any) => (
                        <ElDropdownItem onClick={() => handleIssue(item)}>
                          {item.commandName}
                        </ElDropdownItem>
                      ))}
                    </ElDropdownMenu>
                  )
                }}
              >
                <ElButton type="primary" size="default">
                  查询操作{' '}
                  <ElIcon class="el-icon--right">
                    <ArrowDown />
                  </ElIcon>
                </ElButton>
              </ElDropdown>
            </ElCol>
          </ElRow>
        )}
        {state.ConnectSetVisible && (
          <ConnectSet
            record={state.connectParam}
            visible={state.ConnectSetVisible}
            onCancel={() => handleParamsSet('ConnectSetVisible')}
          />
        )}
        {state.WorkSetVisible && (
          <WorkSet
            record={state.workParam}
            visible={state.WorkSetVisible}
            onCancel={() => handleParamsSet('WorkSetVisible')}
          />
        )}
        {state.LoopSetVisible && (
          <LoopSet
            record={state.loopParam}
            visible={state.LoopSetVisible}
            onCancel={() => handleParamsSet('LoopSetVisible')}
          />
        )}
        {state.AlarmSetVisible && (
          <AlarmSet
            record={state.alarmParam}
            visible={state.AlarmSetVisible}
            onCancel={() => handleParamsSet('AlarmSetVisible')}
          />
        )}
        {state.EventSetVisible && (
          <EventSet
            record={state.eventParam}
            visible={state.EventSetVisible}
            onCancel={() => handleParamsSet('EventSetVisible')}
          />
        )}
        {state.OtherSetVisible && (
          <OtherSet
            record={state.otherParam}
            visible={state.OtherSetVisible}
            onCancel={() => handleParamsSet('OtherSetVisible')}
          />
        )}
        {state.DistrabutionVisible && (
          <DistrabutionList
            visible={state.DistrabutionVisible}
            cancel={onDistrabution}
            onSubmitForm={distrabutionChange}
          />
        )}
        <div style={'text-align: right; margin-top: 24px;'}>
          <ElButton plain size="default" onClick={goBack}>
            取 消
          </ElButton>
          <ElButton type="primary" size="default" onClick={submit}>
            保 存
          </ElButton>
        </div>
      </ElCard>
    )
  }
})
